<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Scrapy,">










<meta name="description" content="本文为慕课网《Python分布式爬虫打造搜索引擎》第四章的学习笔记，主要内容为scrapy爬取知名技术文章网站 视频地址：https://coding.imooc.com/class/92.html">
<meta name="keywords" content="Scrapy">
<meta property="og:type" content="article">
<meta property="og:title" content="【第四章】Python分布式爬虫框架Scrapy打造搜索引擎——scrapy爬取知名技术文章网站">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2019/07/31/python-distributed-spider-4/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文为慕课网《Python分布式爬虫打造搜索引擎》第四章的学习笔记，主要内容为scrapy爬取知名技术文章网站 视频地址：https://coding.imooc.com/class/92.html">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190731144617379.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190731153046705.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190731155953788.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190731161716046.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190731162118167.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190731162232689.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190731165316697.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190801060653563.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190801060852993.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190801060949070.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190731164812346.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190731165003611.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190731174655381.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190801061945255.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190801141940779.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190801143228732.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190801151425224.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190801170950315.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190802061456905.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190731155538657.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190801150430724.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190801150605744.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190801150900548.jpg">
<meta property="og:updated_time" content="2019-08-09T09:36:09.085Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【第四章】Python分布式爬虫框架Scrapy打造搜索引擎——scrapy爬取知名技术文章网站">
<meta name="twitter:description" content="本文为慕课网《Python分布式爬虫打造搜索引擎》第四章的学习笔记，主要内容为scrapy爬取知名技术文章网站 视频地址：https://coding.imooc.com/class/92.html">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20190731144617379.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2019/07/31/python-distributed-spider-4/">





  <title>【第四章】Python分布式爬虫框架Scrapy打造搜索引擎——scrapy爬取知名技术文章网站 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2019/07/31/python-distributed-spider-4/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【第四章】Python分布式爬虫框架Scrapy打造搜索引擎——scrapy爬取知名技术文章网站</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-07-31T11:54:27+08:00">
                2019-07-31
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Python/" itemprop="url" rel="index">
                    <span itemprop="name">Python</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文为慕课网《Python分布式爬虫打造搜索引擎》第四章的学习笔记，主要内容为scrapy爬取知名技术文章网站</p>
<p>视频地址：<a href="https://coding.imooc.com/class/92.html" target="_blank" rel="noopener">https://coding.imooc.com/class/92.html</a></p>
<a id="more"></a>

<h1 id="使用scrapy创建基本模板"><a href="#使用scrapy创建基本模板" class="headerlink" title="使用scrapy创建基本模板"></a>使用scrapy创建基本模板</h1><h2 id="创建基本模板"><a href="#创建基本模板" class="headerlink" title="创建基本模板"></a>创建基本模板</h2><p>参考《第二章》如下图安装完成scrapy后，就可以创建基本模板<br><img src="/blog/images/20190731144617379.jpg" alt="Scrapy框架结构"></p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">cd</span> <span class="selector-tag">ArticleSpider</span></span><br><span class="line"># 因为伯乐在线无法访问，我们更换一个爬取的网址为：<span class="selector-tag">www</span><span class="selector-class">.tianqihoubao</span><span class="selector-class">.com</span></span><br><span class="line"># <span class="selector-tag">scrapy</span> <span class="selector-tag">genspider</span> <span class="selector-tag">jobbole</span> <span class="selector-tag">blog</span><span class="selector-class">.jobbole</span><span class="selector-class">.com</span></span><br><span class="line"><span class="selector-tag">scrapy</span> <span class="selector-tag">genspider</span> <span class="selector-tag">houbao</span> <span class="selector-tag">www</span><span class="selector-class">.tianqihoubao</span><span class="selector-class">.com</span></span><br></pre></td></tr></table></figure>

<p><img src="/blog/images/20190731153046705.jpg" alt="创建基本模板"></p>
<h2 id="为了便于调试，新建main-py"><a href="#为了便于调试，新建main-py" class="headerlink" title="为了便于调试，新建main.py"></a>为了便于调试，新建main.py</h2><p>在ArticleSpider目录下新建main.py文件，在其中编写如下内容</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"># -*- coding: utf<span class="number">-8</span> -*-</span><br><span class="line"></span><br><span class="line">from scrapy.cmdline import <span class="built_in">execute</span></span><br><span class="line">import sys</span><br><span class="line">import <span class="built_in">os</span></span><br><span class="line"></span><br><span class="line"># <span class="built_in">os</span>.<span class="built_in">path</span>.abspath(__file__) 获取当前文件的绝对路径</span><br><span class="line"># <span class="built_in">print</span>(<span class="built_in">os</span>.<span class="built_in">path</span>.abspath(__file__))</span><br><span class="line">sys.<span class="built_in">path</span>.append(<span class="built_in">os</span>.<span class="built_in">path</span>.dirname(<span class="built_in">os</span>.<span class="built_in">path</span>.abspath(__file__)))</span><br><span class="line"></span><br><span class="line"># 运行scrapy项目的命令：scrapy crawl houbao</span><br><span class="line"><span class="built_in">execute</span>([<span class="string">"scrapy"</span>, <span class="string">"crawl"</span>, <span class="string">"houbao"</span>])</span><br></pre></td></tr></table></figure>

<p>运行main.py,结果如下：<br><img src="/blog/images/20190731155953788.jpg" alt="运行main.py"></p>
<h2 id="robots协议需要修改为False"><a href="#robots协议需要修改为False" class="headerlink" title="robots协议需要修改为False"></a>robots协议需要修改为False</h2><p>在运行scrapy的过程中，需要将robots协议修改为False。 因为默认是True，即遵循爬虫协议的，这样可能会过滤掉很多的url导致无法爬取。<br>具体修改为：在 settings.py中</p>
<figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Obey robots.txt rules</span></span><br><span class="line"><span class="attr">ROBOTSTXT_OBEY</span> = <span class="literal">False</span></span><br></pre></td></tr></table></figure>

<h1 id="xpath提取元素"><a href="#xpath提取元素" class="headerlink" title="xpath提取元素"></a>xpath提取元素</h1><h2 id="xpath简介"><a href="#xpath简介" class="headerlink" title="xpath简介"></a>xpath简介</h2><ol>
<li>xpath使用路径表达式在xml和html中进行导航，定位具体元素</li>
<li>xpath包含标准函数库</li>
<li>xpath是一个W3C的标准，所以语法是一致的</li>
</ol>
<h2 id="xpath的节点关系"><a href="#xpath的节点关系" class="headerlink" title="xpath的节点关系"></a>xpath的节点关系</h2><p><strong>父节点、子节点、兄弟节点、先辈节点(祖先节点)、后代节点</strong></p>
<h2 id="xpath的语法"><a href="#xpath的语法" class="headerlink" title="xpath的语法"></a>xpath的语法</h2><p><img src="/blog/images/20190731161716046.jpg" alt="xpath的语法"><br><img src="/blog/images/20190731162118167.jpg" alt="xpath的语法"><br><img src="/blog/images/20190731162232689.jpg" alt="xpath的语法"></p>
<h2 id="通过xpath分析网页"><a href="#通过xpath分析网页" class="headerlink" title="通过xpath分析网页"></a>通过xpath分析网页</h2><p><img src="/blog/images/20190731165316697.jpg" alt="通过xpath分析网页"></p>
<h1 id="css选择器提取元素"><a href="#css选择器提取元素" class="headerlink" title="css选择器提取元素"></a>css选择器提取元素</h1><p><img src="/blog/images/20190801060653563.jpg" alt="css选择器"><br><img src="/blog/images/20190801060852993.jpg" alt="css选择器"><br><img src="/blog/images/20190801060949070.jpg" alt="css选择器"></p>
<h1 id="从具体页面中提取内容"><a href="#从具体页面中提取内容" class="headerlink" title="从具体页面中提取内容"></a>从具体页面中提取内容</h1><h2 id="shell调试页面解析过程"><a href="#shell调试页面解析过程" class="headerlink" title="shell调试页面解析过程"></a>shell调试页面解析过程</h2><p>为了避免每次运行scrapy程序才能获取页面，可以用shell调试scrapy</p>
<figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">scrapy shell http:<span class="regexp">//</span>www.tianqihoubao.com<span class="regexp">/lishi/</span>huhehaote<span class="regexp">/month/</span><span class="number">201801</span>.html</span><br></pre></td></tr></table></figure>

<p><img src="/blog/images/20190731164812346.jpg" alt="shell调试scrapy"><br><img src="/blog/images/20190731165003611.jpg" alt="shell调试scrapy"></p>
<h2 id="xpath提取元素-1"><a href="#xpath提取元素-1" class="headerlink" title="xpath提取元素"></a>xpath提取元素</h2><blockquote>
<p>extract_first() 就是 extract()[0]</p>
</blockquote>
<figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 获取所有的tr元素</span></span><br><span class="line">trs = response.xpath(<span class="string">'//*[@id="content"]/table//tr'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取某一个tr的所有子元素td</span></span><br><span class="line">tds = trs[<span class="number">1</span>].xpath(<span class="string">'*'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取第一个td元素下a元素的文本</span></span><br><span class="line">month = tds[<span class="number">0</span>].xpath(<span class="string">'a/text()'</span>).extract_first().strip()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取第二个td元素下文本</span></span><br><span class="line">weather = re.sub(re.compile(<span class="string">r"[\r\n\s]"</span>,re.S),<span class="string">""</span>,tds[<span class="number">1</span>].xpath(<span class="string">'text()'</span>).extract_first().strip()).split(<span class="string">'/'</span>)</span><br><span class="line">day_weather = weather[<span class="number">0</span>]</span><br><span class="line">night_weather = weather[<span class="number">1</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取第三个td元素下文本</span></span><br><span class="line">temp = re.sub(re.compile(<span class="string">r"[\r\n\s℃']"</span>,re.S),<span class="string">""</span>,tds[<span class="number">2</span>].xpath(<span class="string">'text()'</span>).extract_first().strip()).split(<span class="string">'/'</span>)</span><br><span class="line">day_temp = temp[<span class="number">0</span>]</span><br><span class="line">night_temp = temp[<span class="number">1</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取第四个td元素下文本</span></span><br><span class="line">wind = re.sub(re.compile(<span class="string">r"[\r\n\s']"</span>,re.S),<span class="string">""</span>,tds[<span class="number">3</span>].xpath(<span class="string">'text()'</span>).extract_first().strip()).split(<span class="string">'/'</span>)</span><br><span class="line">day_wind = wind[<span class="number">0</span>]</span><br><span class="line">night_wind = wind[<span class="number">1</span>]</span><br></pre></td></tr></table></figure>

<p><img src="/blog/images/20190731174655381.jpg" alt="shell调试scrapy"></p>
<p>其他xpath的用法:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>. 获取所有<span class="class"><span class="keyword">class</span></span>=<span class="string">"entry-header"</span>的div标签下的h1标签的文本列表中的第一个元素</span><br><span class="line">title = response.xpath(<span class="string">'//div[@class="entry-header"]/h1/text()'</span>).extract_first()</span><br><span class="line"><span class="number">2</span>. 获取所有<span class="class"><span class="keyword">class</span>包含<span class="title">vote</span>-<span class="title">post</span>-<span class="title">up</span>的<span class="title">span</span>标签下的<span class="title">h10</span>标签的文本列表中的第一个元素</span></span><br><span class="line"><span class="class"><span class="title">praise_nums</span> </span>= response.xpath(<span class="string">"//span[contains(@class, 'vote-post-up')]/h10/text()"</span>).extract_first()</span><br></pre></td></tr></table></figure>

<h2 id="css选择器提取元素-1"><a href="#css选择器提取元素-1" class="headerlink" title="css选择器提取元素"></a>css选择器提取元素</h2><blockquote>
<p> Scrapy提供的CSS选择器和Xpath在提取元素方面的功能是完全一样的，具体使用哪一种由开发者喜好决定</p>
</blockquote>
<p>使用css选择器可以实现xpath同样的效果，代码如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 获取所有的tr元素</span></span><br><span class="line">trs = response.css(<span class="string">"#content table tr"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取某一个tr的所有子元素td</span></span><br><span class="line">tds = trs[<span class="number">1</span>].css(<span class="string">'td'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取第一个td元素下a元素的文本，::text为获取文本的伪类选择器</span></span><br><span class="line">date = tds[<span class="number">0</span>].css(<span class="string">'a::text'</span>).extract_first().strip()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取第二个td元素下文本</span></span><br><span class="line">weather = re.sub(re.compile(<span class="string">r"[\r\n\s]"</span>,re.S),<span class="string">""</span>,tds[<span class="number">1</span>].css(<span class="string">'::text'</span>).extract_first().strip()).split(<span class="string">'/'</span>)</span><br><span class="line">day_weather = weather[<span class="number">0</span>]</span><br><span class="line">night_weather = weather[<span class="number">1</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取第三个td元素下文本</span></span><br><span class="line">temp = re.sub(re.compile(<span class="string">r"[\r\n\s℃']"</span>,re.S),<span class="string">""</span>,tds[<span class="number">2</span>].css(<span class="string">'::text'</span>).extract_first().strip()).split(<span class="string">'/'</span>)</span><br><span class="line">day_temp = temp[<span class="number">0</span>]</span><br><span class="line">night_temp = temp[<span class="number">1</span>]</span><br><span class="line">avg_temp = int(temp[<span class="number">0</span>] + temp[<span class="number">1</span>]) / <span class="number">2</span></span><br><span class="line"><span class="comment"># 获取第四个td元素下文本</span></span><br><span class="line">wind = re.sub(re.compile(<span class="string">r"[\r\n\s']"</span>,re.S),<span class="string">""</span>,tds[<span class="number">3</span>].css(<span class="string">'::text'</span>).extract_first().strip()).split(<span class="string">'/'</span>)</span><br><span class="line">day_wind = wind[<span class="number">0</span>]</span><br><span class="line">night_wind = wind[<span class="number">1</span>]</span><br></pre></td></tr></table></figure>

<p><img src="/blog/images/20190801061945255.jpg" alt="css选择器提取元素"></p>
<p>其他CSS选择器的用法:</p>
<figure class="highlight livescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> 获取所有href=<span class="string">"<span class="subst">#article-comment</span>"</span>的a标签下的span标签的文本列表中第一个元素</span><br><span class="line">comment_nums = response.css(<span class="string">"a[href='<span class="subst">#article-comment</span>'] span::text"</span>).extract_first()</span><br></pre></td></tr></table></figure>

<h1 id="爬取列表页面中所有文章的url"><a href="#爬取列表页面中所有文章的url" class="headerlink" title="爬取列表页面中所有文章的url"></a>爬取列表页面中所有文章的url</h1><p>获取列表页面中所有文章的url的关键代码如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> urllib <span class="keyword">import</span> parse</span><br><span class="line"><span class="keyword">from</span> scrapy.http <span class="keyword">import</span> Request</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">parse</span><span class="params">(self, response)</span>:</span></span><br><span class="line">        <span class="string">"""</span></span><br><span class="line"><span class="string">            1. 获取文章列表页中的文章url并交给scrapy下载后并进行具体字段的解析</span></span><br><span class="line"><span class="string">            2. 获取下一页的url并交给scrapy进行下载，下载完成后交给parse函数，执行上述步骤</span></span><br><span class="line"><span class="string">        :param response: 返回下载的网页</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        """</span></span><br><span class="line">        <span class="comment"># 1. 获取文章列表页中的文章url并交给scrapy下载后并进行具体字段的解析</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 1.1 获取文章列表页中的文章url</span></span><br><span class="line">        <span class="comment"># ::attr() 属性伪类选择器</span></span><br><span class="line">        <span class="comment"># 通过css选择器选择a标签的href的值，并提取为url的文本列表</span></span><br><span class="line">        post_urls = response.css(<span class="string">"#content li a::attr(href)"</span>).extract()</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 遍历url列表，为下一步解析页面提供文章完整的url</span></span><br><span class="line">        <span class="keyword">for</span> post_url <span class="keyword">in</span> post_urls:</span><br><span class="line">            print(parse.urljoin(response.url, post_url))</span><br><span class="line">            <span class="comment"># 1.2 交给scrapy下载后并进行具体字段的解析</span></span><br><span class="line">            <span class="comment"># Request的作用：交给scrapy下载传入的url的内容，然后调用回调函数parse_detail</span></span><br><span class="line">            <span class="comment"># 通过meta参数传递值到回调函数中，在回调函数中通过response.meta.get("post_url","")方式获取传入的值</span></span><br><span class="line">            <span class="keyword">yield</span> Request(url=parse.urljoin(response.url, post_url), meta=&#123;<span class="string">"post_url"</span>:post_url&#125;, callback=self.parse_detail)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 2. 获取下一页的url并交给scrapy进行下载，下载完成后执行回调函数parse，重复执行上述步骤</span></span><br><span class="line">        next_url = response.css(<span class="string">".next.page-numbers::attr(href)"</span>).extract_first()</span><br><span class="line">        <span class="keyword">if</span> next_url:</span><br><span class="line">            <span class="keyword">yield</span> Request(url=parse.urljoin(response.url, next_url), callback=self.parse)</span><br></pre></td></tr></table></figure>

<h1 id="创建items模型"><a href="#创建items模型" class="headerlink" title="创建items模型"></a>创建items模型</h1><blockquote>
<p>scrapy的items： 类似字典，定义字段的模型</p>
</blockquote>
<p>在items.py文件中编写如下代码：</p>
<figure class="highlight nix"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">class ArticleItem(scrapy.Item):</span><br><span class="line">    <span class="string">""</span><span class="string">"</span></span><br><span class="line"><span class="string">       文章详情Item</span></span><br><span class="line"><span class="string">    "</span><span class="string">""</span></span><br><span class="line">    <span class="comment"># 定义字段，并指定数据类型，scrapy中只有一种类型————Field</span></span><br><span class="line">    <span class="attr">div_name</span> = scrapy.Field()</span><br><span class="line">    <span class="attr">date</span> = scrapy.Field()</span><br><span class="line">    <span class="attr">day_weather</span> = scrapy.Field()</span><br><span class="line">    <span class="attr">night_weather</span> = scrapy.Field()</span><br><span class="line">    <span class="attr">day_temp</span> = scrapy.Field()</span><br><span class="line">    <span class="attr">night_temp</span> = scrapy.Field()</span><br><span class="line">    <span class="attr">avg_temp</span> = scrapy.Field()</span><br><span class="line">    <span class="attr">day_wind</span> = scrapy.Field()</span><br><span class="line">    <span class="attr">night_wind</span> = scrapy.Field()</span><br><span class="line">    <span class="attr">url</span> = scrapy.Field()</span><br></pre></td></tr></table></figure>

<h1 id="Pipeline的使用"><a href="#Pipeline的使用" class="headerlink" title="Pipeline的使用"></a>Pipeline的使用</h1><blockquote>
<p>pipeline的主要作用：拦截item，用于数据保存</p>
</blockquote>
<ol>
<li><p>修改settings.py使pipeline.py生效</p>
<figure class="highlight makefile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ITEM_PIPELINES = &#123;</span><br><span class="line">   'ArticleSpider.pipelines.ArticlespiderPipeline': 2,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>设置图片自动下载到本地</p>
<figure class="highlight makefile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">ITEM_PIPELINES = &#123;</span><br><span class="line">   'scrapy.pipelines.images.ImagesPipeline': 1,</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment"># 告知pipeline将要下载的图片的url</span></span><br><span class="line">IMAGES_URLS_FIELD = <span class="string">"front_image_url"</span></span><br><span class="line"><span class="comment"># 配置图片保存路径</span></span><br><span class="line">project_dir = os.path.abspath(os.path.dirname(__file__))</span><br><span class="line">IMAGES_STORE = os.path.join(project_dir, <span class="string">"images"</span>)</span><br><span class="line"><span class="comment"># 设置允许下载图片的最小高度、最小宽度</span></span><br><span class="line">IMAGES_MIN_HEIGHT = 100</span><br><span class="line">IMAGES_MIN_WIDTH = 100</span><br></pre></td></tr></table></figure>

</li>
</ol>
<blockquote>
<p>注意：如果报错’No Module named PIL’，则需要安装pillow库，安装命令如下: </p>
</blockquote>
<figure class="highlight cmake"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip <span class="keyword">install</span> pillow</span><br></pre></td></tr></table></figure>

<blockquote>
<p>注意：front_image_url的值必须是数组</p>
</blockquote>
<h1 id="通过pipeline保存item到本地json文件中"><a href="#通过pipeline保存item到本地json文件中" class="headerlink" title="通过pipeline保存item到本地json文件中"></a>通过pipeline保存item到本地json文件中</h1><h2 id="自定义保存数据到JSON文件中的pipeline"><a href="#自定义保存数据到JSON文件中的pipeline" class="headerlink" title="自定义保存数据到JSON文件中的pipeline"></a>自定义保存数据到JSON文件中的pipeline</h2><ol>
<li><p>编写保存数据到JSON文件中的pipeline</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">JsonWithEncodingPipeline</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="string">"""保存数据到本地的JSON文件中"""</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="comment"># 打开json文件, codecs的open()方法处理了编码的复杂问题</span></span><br><span class="line">        self.file = codecs.open(<span class="string">'article.json'</span>, <span class="string">'w'</span>, encoding=<span class="string">'utf-8'</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">process_item</span><span class="params">(self, item, spider)</span>:</span></span><br><span class="line">        <span class="string">"""</span></span><br><span class="line"><span class="string">           处理item的方法，将item写入json文件</span></span><br><span class="line"><span class="string">        :param item:</span></span><br><span class="line"><span class="string">        :param spider:</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        """</span></span><br><span class="line">        <span class="comment"># ensure_ascii需指定为False，避免中文等编码直接写入到文件中导致乱码</span></span><br><span class="line">        lines = json.dump(dict(item), ensure_ascii=<span class="literal">False</span>) + <span class="string">"\n"</span></span><br><span class="line">        self.file.write(lines)</span><br><span class="line">        <span class="keyword">return</span> item</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">spider_closed</span><span class="params">(self,spider)</span>:</span></span><br><span class="line">        <span class="string">"""</span></span><br><span class="line"><span class="string">            当spider关闭时执行该方法————关闭文件</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        """</span></span><br><span class="line">        self.file.close()</span><br></pre></td></tr></table></figure>
</li>
<li><p>在setting.py中配置该pipeline</p>
<figure class="highlight makefile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 数字表示该pipeline调用的优先级，越小越优先调用</span></span><br><span class="line">ITEM_PIPELINES = &#123;</span><br><span class="line">   'ArticleSpider.pipelines.JsonWithEncodingPipeline': 5,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h2 id="使用Scrapy提供的保存数据到JSON文件中的pipeline"><a href="#使用Scrapy提供的保存数据到JSON文件中的pipeline" class="headerlink" title="使用Scrapy提供的保存数据到JSON文件中的pipeline"></a>使用Scrapy提供的保存数据到JSON文件中的pipeline</h2><ol>
<li>使用scrapy提供的JsonItemExporter创建pipeline</li>
</ol>
<figure class="highlight ruby"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">JsonExporterPipeline</span>(<span class="title">object</span>):</span></span><br><span class="line">    <span class="string">""</span><span class="string">"</span></span><br><span class="line"><span class="string">        使用scrapy提供的JsonItemExporter保存数据到本地的JSON文件中</span></span><br><span class="line"><span class="string">    "</span><span class="string">""</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(<span class="keyword">self</span>)</span></span><span class="symbol">:</span></span><br><span class="line">        <span class="comment"># 直接使用open()方法打开json文件</span></span><br><span class="line">        <span class="keyword">self</span>.file = open(<span class="string">'article_exporter.json'</span>, <span class="string">'wb'</span>)</span><br><span class="line">        <span class="keyword">self</span>.exporter = JsonItemExporter(<span class="keyword">self</span>.file, encoding=<span class="string">"utf-8"</span>, ensure_ascii=False)</span><br><span class="line">        <span class="keyword">self</span>.exporter.start_exporting()</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">close_spider</span><span class="params">(<span class="keyword">self</span>, spider)</span></span><span class="symbol">:</span></span><br><span class="line">        <span class="keyword">self</span>.exporter.finish_exporting()</span><br><span class="line">        <span class="keyword">self</span>.file.close()</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">process_item</span><span class="params">(<span class="keyword">self</span>, item, spider)</span></span><span class="symbol">:</span></span><br><span class="line">        <span class="keyword">self</span>.exporter.export_item(item)</span><br><span class="line">        <span class="keyword">return</span> item</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>在setting.py中配置该pipeline<figure class="highlight makefile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ITEM_PIPELINES = &#123;</span><br><span class="line">   'ArticleSpider.pipelines.JsonExporterPipeline': 5,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h1 id="通过pipeline保存数据到数据库"><a href="#通过pipeline保存数据到数据库" class="headerlink" title="通过pipeline保存数据到数据库"></a>通过pipeline保存数据到数据库</h1><ol>
<li><p>pycharm连接数据库<br><img src="/blog/images/20190801141940779.jpg" alt="缺少pypiwin32模块"></p>
</li>
<li><p>数据表设计</p>
<blockquote>
<p>注意： 如果url是唯一的，则需要将curr_url_md5_id设置为主键，这样便于后续更新这条url的数据<br><img src="/blog/images/20190801143228732.jpg" alt="数据表设计"></p>
</blockquote>
</li>
<li><p>安装pgsql驱动</p>
<figure class="highlight cmake"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip <span class="keyword">install</span> psycopg2</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20190801151425224.jpg" alt="安装pgsql驱动"></p>
<h2 id="采用同步机制将数据保存到数据库的pipeline方式"><a href="#采用同步机制将数据保存到数据库的pipeline方式" class="headerlink" title="采用同步机制将数据保存到数据库的pipeline方式"></a>采用同步机制将数据保存到数据库的pipeline方式</h2><ol>
<li><p>自定义同步机制的pipeline</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">PgSQLPipeline</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="string">"""</span></span><br><span class="line"><span class="string">       自定义同步机制保存数据到pgsql数据库中的pipeline</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="comment"># 连接数据库</span></span><br><span class="line">        self.conn = psycopg2.connect(database=<span class="string">"postgres"</span>, user=<span class="string">"postgres"</span>,</span><br><span class="line">                                     password=<span class="string">"xxxx"</span>, host=<span class="string">"127.0.0.1"</span>, port=<span class="string">"5432"</span>)</span><br><span class="line">        self.cursor = self.conn.cursor()</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">process_item</span><span class="params">(self, item, spider)</span>:</span></span><br><span class="line">        insert_sql = <span class="string">"""</span></span><br><span class="line"><span class="string">                insert into public.weather_history </span></span><br><span class="line"><span class="string">                (div_name, hb_date, day_weather,night_weather,day_temp,night_temp,avg_temp,</span></span><br><span class="line"><span class="string">                day_wind,night_wind,curr_url,curr_url_md5_id) </span></span><br><span class="line"><span class="string">                values</span></span><br><span class="line"><span class="string">                (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)</span></span><br><span class="line"><span class="string">        """</span></span><br><span class="line">        <span class="comment"># 将数据插入数据库</span></span><br><span class="line">        self.cursor.execute(insert_sql, (item[<span class="string">"div_name"</span>], item[<span class="string">"hb_date"</span>], item[<span class="string">"day_weather"</span>], item[<span class="string">"night_weather"</span>],</span><br><span class="line">                                         item[<span class="string">"day_temp"</span>], item[<span class="string">"night_temp"</span>], item[<span class="string">"avg_temp"</span>], item[<span class="string">"day_wind"</span>],</span><br><span class="line">                                         item[<span class="string">"night_wind"</span>], item[<span class="string">"curr_url"</span>], item[<span class="string">"curr_url_md5_id"</span>]))</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 提交事务</span></span><br><span class="line">        self.conn.commit()</span><br><span class="line">        <span class="keyword">return</span> item</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">spider_closed</span><span class="params">(self, spider)</span>:</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 关闭连接</span></span><br><span class="line">        self.conn.close()</span><br></pre></td></tr></table></figure>
</li>
<li><p>在setting.py中配置该pipeline</p>
<figure class="highlight makefile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ITEM_PIPELINES = &#123;</span><br><span class="line">   'ArticleSpider.pipelines.PgSQLPipeline': 4,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>插入结果<br><img src="/blog/images/20190801170950315.jpg" alt="插入结果"></p>
</li>
</ol>
<h2 id="采用异步机制将数据保存到数据库的pipeline方式"><a href="#采用异步机制将数据保存到数据库的pipeline方式" class="headerlink" title="采用异步机制将数据保存到数据库的pipeline方式"></a>采用异步机制将数据保存到数据库的pipeline方式</h2><blockquote>
<p>使用第一种pipeline方式，会因爬取的item大量增加导致插入数据库的操作过慢而阻塞，因此需要引入异步插入操作<br>（第一种pipeline是同步插入的方式）</p>
</blockquote>
<pre><code>注意： 使用Twisted进行异步插入只需按照如下套路编写即可，
      唯一需要修改的就是do_insert中的具体插入逻辑</code></pre><ol>
<li><p>自定义异步机制的pipeline</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> psycopg2</span><br><span class="line"><span class="keyword">from</span> twisted.enterprise <span class="keyword">import</span> adbapi</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">PgSQLAsyncTwistedPipeline</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="string">"""</span></span><br><span class="line"><span class="string">        自定义保存数据到pgsql数据库中的pipeline，异步插入</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 类方法，类加载时调用，用于读取setting.py文件在的配置项</span></span><br><span class="line"><span class="meta">    @classmethod</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">from_settings</span><span class="params">(cls, settings)</span>:</span></span><br><span class="line">        <span class="string">"""</span></span><br><span class="line"><span class="string">            读取setting.py文件中的配置项</span></span><br><span class="line"><span class="string">        :param settings:</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        """</span></span><br><span class="line">        dbparms = dict(</span><br><span class="line">            host=settings[<span class="string">"PGSQL_HOST"</span>],</span><br><span class="line">            port=settings[<span class="string">"PGSQL_PORT"</span>],</span><br><span class="line">            user=settings[<span class="string">"PGSQL_USER"</span>],</span><br><span class="line">            database=settings[<span class="string">"PGSQ_DBNAME"</span>],</span><br><span class="line">            password=settings[<span class="string">"PGSQL_PASSWORD"</span>]</span><br><span class="line">        )</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 异步连接池</span></span><br><span class="line">        dbpool = adbapi.ConnectionPool(<span class="string">"psycopg2"</span>, **dbparms)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> cls(dbpool)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, dbpool)</span>:</span></span><br><span class="line">        self.dbpool = dbpool</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">process_item</span><span class="params">(self, item, spider)</span>:</span></span><br><span class="line">        <span class="string">"""</span></span><br><span class="line"><span class="string">           使用Twisted将gpsql插入变成异步执行</span></span><br><span class="line"><span class="string">        :param item:</span></span><br><span class="line"><span class="string">        :param spider:</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        """</span></span><br><span class="line">        <span class="comment"># 执行异步插入操作</span></span><br><span class="line">        query = self.dbpool.runInteraction(self.do_insert, item)</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 处理异常</span></span><br><span class="line">        query.addErrback(self.error_handler, item, spider)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> item</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">do_insert</span><span class="params">(self, cursor, item)</span>:</span></span><br><span class="line">        <span class="string">"""</span></span><br><span class="line"><span class="string">            具体的插入逻辑</span></span><br><span class="line"><span class="string">        :param cursor:</span></span><br><span class="line"><span class="string">        :param item:</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        """</span></span><br><span class="line">        insert_sql = <span class="string">"""</span></span><br><span class="line"><span class="string">                insert into public.weather_history </span></span><br><span class="line"><span class="string">                (div_name, hb_date, day_weather,night_weather,day_temp,night_temp,avg_temp,</span></span><br><span class="line"><span class="string">                day_wind,night_wind,curr_url,curr_url_md5_id) </span></span><br><span class="line"><span class="string">                values</span></span><br><span class="line"><span class="string">                (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)</span></span><br><span class="line"><span class="string">        """</span></span><br><span class="line">        <span class="comment"># 将数据插入数据库</span></span><br><span class="line">        cursor.execute(insert_sql, (item[<span class="string">"div_name"</span>], item[<span class="string">"hb_date"</span>], item[<span class="string">"day_weather"</span>], item[<span class="string">"night_weather"</span>],</span><br><span class="line">                                    item[<span class="string">"day_temp"</span>], item[<span class="string">"night_temp"</span>], item[<span class="string">"avg_temp"</span>], item[<span class="string">"day_wind"</span>],</span><br><span class="line">                                    item[<span class="string">"night_wind"</span>], item[<span class="string">"curr_url"</span>], item[<span class="string">"curr_url_md5_id"</span>]))</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">error_handler</span><span class="params">(self, failure, item, spider)</span>:</span></span><br><span class="line">        <span class="string">"""</span></span><br><span class="line"><span class="string">            处理异步插入异常</span></span><br><span class="line"><span class="string">        :param failure:</span></span><br><span class="line"><span class="string">        :param item:</span></span><br><span class="line"><span class="string">        :param spider:</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        """</span></span><br><span class="line">        print(failure)</span><br></pre></td></tr></table></figure>
</li>
<li><p>在setting.py文件中配置pipeline等如下信息</p>
<figure class="highlight makefile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">ITEM_PIPELINES = &#123;</span><br><span class="line">    'ArticleSpider.pipelines.PgSQLAsyncTwistedPipeline': 5</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment"># Pgsql config</span></span><br><span class="line">PGSQL_HOST = '127.0.0.1'</span><br><span class="line">PGSQL_PORT = '5432'</span><br><span class="line">PGSQL_USER = 'postgres'</span><br><span class="line">PGSQ_DBNAME = 'postgres'</span><br><span class="line">PGSQL_PASSWORD = 'xxxx'</span><br></pre></td></tr></table></figure>
</li>
<li><p>插入结果<br><img src="/blog/images/20190802061456905.jpg" alt="插入结果"></p>
</li>
</ol>
<h1 id="scrapy-item-loader机制"><a href="#scrapy-item-loader机制" class="headerlink" title="scrapy item loader机制"></a>scrapy item loader机制</h1><blockquote>
<p>itemLoader机制： 简化维护xpath或css提取元素的规则<br>优点： 可以配置CSS提取规则，而无需修改代码</p>
</blockquote>
<ol>
<li><p>在自定义的Spider类中，定义通过itemloader进行文章具体字段的解析的方法</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">HoubaoSpider</span><span class="params">(scrapy.Spider)</span>:</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 忽略代码</span></span><br><span class="line">    <span class="comment"># 忽略代码</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">parse_detail_with_item_loader</span><span class="params">(self, response)</span>:</span></span><br><span class="line">        <span class="string">"""</span></span><br><span class="line"><span class="string">            scrapy下载具体页面并使用scrapy提供的itemloader进行文章具体字段的解析</span></span><br><span class="line"><span class="string">            使用的功能同parse_detail()方法</span></span><br><span class="line"><span class="string">        :param response:</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        """</span></span><br><span class="line">        <span class="comment"># ItemLoader配置特定元素的CSS或Xpath提取规则</span></span><br><span class="line">        <span class="comment"># 通过Itemloader加载Item</span></span><br><span class="line">        item_loader = ArticleItemLoader(item=HouBaoArticleItem(), response=response)</span><br><span class="line">        <span class="comment"># add_css()方法中的第一个参数为HouBaoArticleItem中的属性名，</span></span><br><span class="line">        <span class="comment"># add_css()方法中的第二个参数为对应属性的具体css提取规则</span></span><br><span class="line">        item_loader.add_css(<span class="string">'title_loader'</span>, <span class="string">'#content h1::text'</span>)</span><br><span class="line">        item_loader.add_value(<span class="string">"curr_url"</span>, response.url)</span><br><span class="line">        item_loader.add_value(<span class="string">"curr_url_md5_id"</span>, get_md5(response.url))</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 解析规则，生成article_item</span></span><br><span class="line">        article_item = item_loader.load_item()</span><br><span class="line"></span><br><span class="line">        <span class="keyword">yield</span> article_item</span><br></pre></td></tr></table></figure>
</li>
<li><p>在Item模型中添加处理方法</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> scrapy.loader.processors <span class="keyword">import</span> MapCompose, TakeFirst</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ArticleItemLoader</span><span class="params">(ItemLoader)</span>:</span></span><br><span class="line">    <span class="string">"""</span></span><br><span class="line"><span class="string">        自定义ItemLoader，重写default_output_processor，</span></span><br><span class="line"><span class="string">        避免了Item的每个Field都需要设置output_processor为TakeFirst()</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line">    default_output_processor = TakeFirst()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 过滤Field的方法    </span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_div_name</span><span class="params">(value)</span>:</span></span><br><span class="line">    <span class="string">"""</span></span><br><span class="line"><span class="string">        处理title_loader通过CSS或Xpath规则获取到的list,返回divname</span></span><br><span class="line"><span class="string">    :param value: title_loader通过CSS或Xpath规则获取到的list</span></span><br><span class="line"><span class="string">    :return:</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line">    title_match = re.match(<span class="string">r'(.*)历史天气预报.*'</span>, value.strip())</span><br><span class="line">    <span class="keyword">if</span> title_match:</span><br><span class="line">        div_name = title_match.group(<span class="number">1</span>)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        div_name = <span class="string">""</span></span><br><span class="line">    <span class="keyword">return</span> div_name</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">HouBaoArticleItem</span><span class="params">(scrapy.Item)</span>:</span></span><br><span class="line">    <span class="string">"""</span></span><br><span class="line"><span class="string">       天气后报文章详情Item</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line">    <span class="comment"># 使用itemloader的示例，添加预处理函数</span></span><br><span class="line">    div_name = scrapy.Field(</span><br><span class="line">        <span class="comment"># input_processor预处理函数，处理Field的值</span></span><br><span class="line">        input_processor=MapCompose(get_div_name),</span><br><span class="line">        <span class="comment"># TakeFirst取list的第一项，使用ArticleItemLoader后可省略该项</span></span><br><span class="line">        output_processor=TakeFirst()</span><br><span class="line">    )</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h1 id="常见错误"><a href="#常见错误" class="headerlink" title="常见错误"></a>常见错误</h1><h2 id="ModuleNotFoundError-No-module-named-‘win32api’"><a href="#ModuleNotFoundError-No-module-named-‘win32api’" class="headerlink" title="ModuleNotFoundError: No module named ‘win32api’"></a>ModuleNotFoundError: No module named ‘win32api’</h2><p>错误原因：缺少pypiwin32模块<br>解决方法：</p>
<figure class="highlight cmake"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip <span class="keyword">install</span> pypiwin32</span><br></pre></td></tr></table></figure>

<p><img src="/blog/images/20190731155538657.jpg" alt="缺少pypiwin32模块"></p>
<h2 id="ModuleNotFoundError-No-module-named-‘PIL’"><a href="#ModuleNotFoundError-No-module-named-‘PIL’" class="headerlink" title="ModuleNotFoundError: No module named ‘PIL’"></a>ModuleNotFoundError: No module named ‘PIL’</h2><p>错误原因： 缺少pillow模块<br>解决方法：</p>
<figure class="highlight cmake"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip <span class="keyword">install</span> pillow</span><br></pre></td></tr></table></figure>

<p><img src="/blog/images/20190801150430724.jpg" alt="缺少pillow模块"></p>
<h2 id="Unresolved-reference-‘xxx’"><a href="#Unresolved-reference-‘xxx’" class="headerlink" title="Unresolved reference ‘xxx’"></a>Unresolved reference ‘xxx’</h2><p>导入外部模块时，出现Unresolved reference ‘xxx’的错误，如下图：<br><img src="/blog/images/20190801150605744.jpg" alt="Unresolved reference &#39;xxx&#39;"></p>
<p>解决办法：</p>
<blockquote>
<p>在项目上 单击右键 -&gt; Mark Directory as -&gt; Sources Root 即可解决</p>
</blockquote>
<p><img src="/blog/images/20190801150900548.jpg" alt="解决Unresolved reference &#39;xxx&#39;"></p>
<h2 id="Scrapy爬虫不执行yield请求"><a href="#Scrapy爬虫不执行yield请求" class="headerlink" title="Scrapy爬虫不执行yield请求"></a>Scrapy爬虫不执行yield请求</h2><p>执行scrapy爬虫时，遇到了不执行yield的情况</p>
<p>参考：<a href="https://blog.csdn.net/qq_32670879/article/details/85042464" target="_blank" rel="noopener">https://blog.csdn.net/qq_32670879/article/details/85042464</a></p>
<p>错误原因：<br>   在allowed_domains数组中填写了不正确的请求域名，将爬虫的url过滤掉了</p>
<p>解决方法：</p>
<ol>
<li>将请求的域名（如：<a href="http://www.tianqihoubao.com" target="_blank" rel="noopener">www.tianqihoubao.com</a> )添加到spider爬虫文件的allowed_domains数组中，域名后不需要添加‘/’号，否则会将我们正常的请求过滤掉</li>
</ol>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Scrapy/" rel="tag"># Scrapy</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/07/31/python-distributed-spider-3/" rel="next" title="【第三章】Python分布式爬虫框架Scrapy打造搜索引擎——爬虫基础知识">
                <i class="fa fa-chevron-left"></i> 【第三章】Python分布式爬虫框架Scrapy打造搜索引擎——爬虫基础知识
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/08/08/tensorFlow-step-by-step-1/" rel="prev" title="【第一章】Google工程师亲授 Tensorflow2.0－入门到进阶——Tensorflow2简介与环境搭建">
                【第一章】Google工程师亲授 Tensorflow2.0－入门到进阶——Tensorflow2简介与环境搭建 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#使用scrapy创建基本模板"><span class="nav-number">1.</span> <span class="nav-text">使用scrapy创建基本模板</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#创建基本模板"><span class="nav-number">1.1.</span> <span class="nav-text">创建基本模板</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#为了便于调试，新建main-py"><span class="nav-number">1.2.</span> <span class="nav-text">为了便于调试，新建main.py</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#robots协议需要修改为False"><span class="nav-number">1.3.</span> <span class="nav-text">robots协议需要修改为False</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#xpath提取元素"><span class="nav-number">2.</span> <span class="nav-text">xpath提取元素</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#xpath简介"><span class="nav-number">2.1.</span> <span class="nav-text">xpath简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#xpath的节点关系"><span class="nav-number">2.2.</span> <span class="nav-text">xpath的节点关系</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#xpath的语法"><span class="nav-number">2.3.</span> <span class="nav-text">xpath的语法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#通过xpath分析网页"><span class="nav-number">2.4.</span> <span class="nav-text">通过xpath分析网页</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#css选择器提取元素"><span class="nav-number">3.</span> <span class="nav-text">css选择器提取元素</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#从具体页面中提取内容"><span class="nav-number">4.</span> <span class="nav-text">从具体页面中提取内容</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#shell调试页面解析过程"><span class="nav-number">4.1.</span> <span class="nav-text">shell调试页面解析过程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#xpath提取元素-1"><span class="nav-number">4.2.</span> <span class="nav-text">xpath提取元素</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#css选择器提取元素-1"><span class="nav-number">4.3.</span> <span class="nav-text">css选择器提取元素</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#爬取列表页面中所有文章的url"><span class="nav-number">5.</span> <span class="nav-text">爬取列表页面中所有文章的url</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#创建items模型"><span class="nav-number">6.</span> <span class="nav-text">创建items模型</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Pipeline的使用"><span class="nav-number">7.</span> <span class="nav-text">Pipeline的使用</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#通过pipeline保存item到本地json文件中"><span class="nav-number">8.</span> <span class="nav-text">通过pipeline保存item到本地json文件中</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#自定义保存数据到JSON文件中的pipeline"><span class="nav-number">8.1.</span> <span class="nav-text">自定义保存数据到JSON文件中的pipeline</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用Scrapy提供的保存数据到JSON文件中的pipeline"><span class="nav-number">8.2.</span> <span class="nav-text">使用Scrapy提供的保存数据到JSON文件中的pipeline</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#通过pipeline保存数据到数据库"><span class="nav-number">9.</span> <span class="nav-text">通过pipeline保存数据到数据库</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#采用同步机制将数据保存到数据库的pipeline方式"><span class="nav-number">9.1.</span> <span class="nav-text">采用同步机制将数据保存到数据库的pipeline方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#采用异步机制将数据保存到数据库的pipeline方式"><span class="nav-number">9.2.</span> <span class="nav-text">采用异步机制将数据保存到数据库的pipeline方式</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#scrapy-item-loader机制"><span class="nav-number">10.</span> <span class="nav-text">scrapy item loader机制</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#常见错误"><span class="nav-number">11.</span> <span class="nav-text">常见错误</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#ModuleNotFoundError-No-module-named-‘win32api’"><span class="nav-number">11.1.</span> <span class="nav-text">ModuleNotFoundError: No module named ‘win32api’</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ModuleNotFoundError-No-module-named-‘PIL’"><span class="nav-number">11.2.</span> <span class="nav-text">ModuleNotFoundError: No module named ‘PIL’</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Unresolved-reference-‘xxx’"><span class="nav-number">11.3.</span> <span class="nav-text">Unresolved reference ‘xxx’</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Scrapy爬虫不执行yield请求"><span class="nav-number">11.4.</span> <span class="nav-text">Scrapy爬虫不执行yield请求</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
